/*
 * @Author: i@douxuefeng.cn
 * @Date: 2021-12-18 18:14:21
 * @LastEditTime: 2021-12-18 18:14:21
 * @LastEditors: i@douxuefeng.cn
 * @Description:
 * @FilePath: \mountain\utils\files.go
 */
package utils

import (
	"errors"
	"fmt"
	"mime/multipart"
	"path"
	"strconv"
	"strings"
	"time"

	comm "gitee.com/douxuefeng/go-utils"
	"gitee.com/douxuefeng/go-utils/strs"
	"github.com/kataras/iris/v12"
)

const (
	max = 5 << 20
)

func SaveFile(c iris.Context) (string, error) {
	dest := "./public/uploads/" + time.Now().Format("2006-01-02") + "/"
	if !comm.NewFile.IsExist(dest) {
		comm.NewFile.CreateFile(dest)
	}
	f, fh, err := c.FormFile("file")
	if err != nil {
		fmt.Println(err)
		return "", errors.New("请添加文件上传")
	}
	defer f.Close()
	if fh.Size > max {
		return "", errors.New("上传文件不得超过5M")
	}
	// 对文件重命名
	filename := dest + strconv.FormatInt(time.Now().Unix(), 10) + strs.GetRandomNumber(6) + strings.ToLower(path.Ext(fh.Filename))
	_, err = c.SaveFormFile(fh, filename)
	if err != nil {
		return "", err
	}
	filename = strings.Replace(filename, "./public", "", 1)
	return filename, nil
}

func SaveFiles(c iris.Context) ([]string, error) {
	dest := "./public/uploads/" + time.Now().Format("2006-01-02") + "/"
	if !comm.NewFile.IsExist(dest) {
		comm.NewFile.CreateFile(dest)
	}
	var filenames []string
	_, n, err := c.UploadFormFiles(dest, func(_ iris.Context, fh *multipart.FileHeader) bool {
		fh.Filename = strconv.FormatInt(time.Now().Unix(), 10) + strs.GetRandomNumber(6) + strings.ToLower(path.Ext(fh.Filename))
		filenames = append(filenames, strings.Replace(path.Join(dest, fh.Filename), "public", "", 1))
		return true
	})
	if err != nil {
		return nil, err
	}

	if n == 0 {
		return nil, errors.New("请上传文件")
	}
	return filenames, nil
}
